import { FC, useState, useEffect, useRef } from 'react';
import { Divider, Space, Table, Button, message, Spin, Pagination } from 'antd';
import { Link, useLocation } from 'react-router-dom';
import { smallPolicyTableInfoApi } from '@apis/invoiceApis';
import { SmallPolicySearchForm } from './smallPolicySearchForm';
import { chinaDate, deepClone } from '@src/utils';
import { useCurrentSize } from '@src/utils/useIndex';

export const SmallPolicy: FC = () => {
  let pageUseHistory = useLocation();
  console.log(pageUseHistory);
  useEffect(() => {
    //默认进来不查询页面
    // console.log('默认进来查询页面');
    // getPageList();
    return () => {};
  }, []);
  const { pageInfo, setPageInfo } = useCurrentSize();
  const [pageListData, setPageListData] = useState<any>({});
  const [colums] = useState<any>([
    {
      title: '投保订单号',
      dataIndex: 'proposalOrder',
      key: 'proposalOrder',
      width: 100,
    },
    {
      title: '业务类型',
      dataIndex: 'productItemTypeFraDictName',
      key: 'productItemTypeFraDictName',
      width: 100,
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 100,
    },
    {
      title: '计划代码',
      dataIndex: 'planCode',
      key: 'planCode',
      width: 100,
    },
    {
      title: '核心保单号',
      dataIndex: 'policyNo',
      key: 'policyNo',
      width: 100,
    },
    {
      title: '订单创建时间起',
      dataIndex: 'startDate',
      key: 'businessDateMin',
      width: 140,
    },
    {
      title: '订单创建时间止',
      dataIndex: 'endDate',
      key: 'businessDateMax',
      width: 140,
    },
    {
      title: '退保状态',
      dataIndex: 'surrenderStatus',
      key: 'surrenderStatus',
      render: (text: any, record: any) => <span>{text === 1 ? '已退保' : '未退保'}</span>,
      width: 80,
    },
    // {
    //   title: '主商品订单号?',
    //   dataIndex: 'channelOrder',
    //   key: 'channelOrder',
    //   width: 100,
    // },
    // {
    //   title: '服务商品订单号?',
    //   dataIndex: 'channelServiceOrder',
    //   key: 'channelServiceOrder',
    //   width: 100,
    // },
    // {
    //   title: '商家ID?',
    //   dataIndex: 'venderID',
    //   key: 'venderID',
    //   width: 100,
    // },
    {
      title: '操作',
      key: 'Actions',
      width: 100,
      fixed: 'right',
      render: (text: any, record: any) => (
        <Link to={`/smallPolicy/detail?orderNo=${encodeURIComponent(record.orderNo)}`}>查看</Link>
      ),
    },
  ]);
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const ajaxParams: any = useRef({});
  const searchBtnF = (formValue: any) => {
    console.log('点击了搜索', formValue);
    let businessDateMin: any = null;
    let businessDateMax: any = null;
    if (formValue.smallPolicyCreateDate?.length > 0) {
      let dateObj = [
        chinaDate(formValue.smallPolicyCreateDate[0].$d.getTime()),
        chinaDate(formValue.smallPolicyCreateDate[1].$d.getTime()),
      ];
      businessDateMin = dateObj[0].date0;
      businessDateMax = dateObj[1].date59;
    }
    let { smallPolicyCreateDate, ...delFormValue } = formValue;
    ajaxParams.current = { ...delFormValue, businessDateMin, businessDateMax };
    console.log('参数是', ajaxParams.current);
    getPageList(1, ajaxParams.current.size || pageInfo.size);
  };
  const getPageList = (current?: any, size?: any) => {
    // console.trace();
    let canshu: any = {
      ...ajaxParams.current,
    };
    canshu.current = current || ajaxParams.current.current || pageInfo.current;
    canshu.size = size || ajaxParams.current.size || pageInfo.size;
    console.log(JSON.parse(JSON.stringify({ canshu })));
    setTableLoading(true);
    smallPolicyTableInfoApi(canshu)
      .then((result: any) => {
        console.log(result);
        if (
          /*如果后台返回值没有数据 并且并非是在第一页*/
          result.data?.model?.length === 0 &&
          result.data?.current !== 1
        ) {
          getPageList(1, canshu.size);
          return;
        }
        setPageListData(result.data);
        setPageInfo({
          current: result.data.current,
          size: result.data.size,
        });
      })
      .catch((err: any) => {
        console.log(err);
      })
      .finally(() => {
        setTableLoading(false);
      });
  };

  const paginationChange = (pageNo: number, pageSize: any) => {
    console.log('pageNo=' + pageNo, 'pageSize=' + pageSize);
    getPageList(pageNo, pageSize);
  };

  const showTotal = () => {
    return `${pageListData?.total || 0}条记录`;
  };
  return (
    <div className="pageBox">
      <Spin spinning={tableLoading} delay={100}>
        <SmallPolicySearchForm searchBtnF={searchBtnF} />
        <div className="anTableBox margT10">
          <Table
            size={'small'}
            scroll={{ x: '100%' }}
            dataSource={pageListData?.model || []}
            columns={colums}
            rowKey={(record) => record.channelEndorOrder || Math.random()}
            pagination={false}
          />
          <Pagination
            hideOnSinglePage={true}
            style={{ textAlign: 'right', margin: '10px 0 0 0' }}
            size="small"
            current={pageInfo.current}
            pageSize={pageInfo.size}
            total={pageListData?.total || 0}
            showTotal={showTotal}
            onChange={paginationChange}
            showSizeChanger
            showQuickJumper
          />
        </div>
      </Spin>
    </div>
  );
};
